//
//  PlantSet+CRUD.m
//  PlotMate
//
//  Created by Brian Boyle on 01/04/2012.
//  Copyright (c) 2012 Brian Boyle. All rights reserved.
//

#import "PlantSet+CRUD.h"

@implementation PlantSet (CRUD)


+(NSArray *)addPlantNameToNSUserDefaults:(NSString *)plantName
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSMutableArray *plantSetArray = [[prefs objectForKey:@"PlantSet"] mutableCopy];
    if(plantSetArray == nil){
        plantSetArray = [[NSMutableArray alloc] init];
    }
    if([plantSetArray containsObject:plantName]){
        //Just return nil if the plant is already in the list. We will handle the alert to the user in the view.
        return nil;
    }
    [plantSetArray addObject:plantName];
    [prefs setObject:plantSetArray forKey:@"PlantSet"];
    return plantSetArray;
}

+(void)deletePlantNameFromNSUserDefaults:(NSString *)plantName
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    NSMutableArray *plantSetArray = [[prefs objectForKey:@"PlantSet"] mutableCopy];
    [plantSetArray removeObject:plantName];
    [prefs setObject:plantSetArray forKey:@"PlantSet"];
}

+(void)deleteAllPlantSetFromNSUserDefaults
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs removeObjectForKey:@"PlantSet"];
}

+(NSMutableArray *)getPlantSetFromNSUserDefaults
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    return [[prefs objectForKey:@"PlantSet"] mutableCopy];
}

+(int)countPlantsPlantSetArray
{
    if([self getPlantSetFromNSUserDefaults] == nil){
        return 0;
    }
    return [[self getPlantSetFromNSUserDefaults] count]; 
}

+(PlantSet *)createPlantSetWithName:(NSString *)name plants:(NSArray *)plantsArray inContext:(NSManagedObjectContext *)context
{
    PlantSet *plantSet = [NSEntityDescription insertNewObjectForEntityForName:@"PlantSet" inManagedObjectContext:context];
    plantSet.name = name;
    [plantSet addPlants:[NSSet setWithArray:plantsArray]];
    return plantSet;
}

+(NSArray *)getAllPlantSetsInContext:(NSManagedObjectContext *)context
{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"PlantSet"];
    NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    request.sortDescriptors = [NSArray arrayWithObject:sorter];
    
    NSError *error;
    return [context executeFetchRequest:request error:&error];
}

+(void)deletePlantSet:(PlantSet *)plantSet inContext:(NSManagedObjectContext *)context
{
    [context deleteObject:plantSet];
    NSError *error;
    [context save:&error];
}
@end
